<?php

namespace App\Admin\Controllers;

use Dcat\Admin\Http\Controllers\AuthController as BaseAuthController;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Http\Repositories\Administrator;
use Dcat\Admin\Layout\Content;
use WpLogin\Login\Http\Controllers\LoginController as WpLoginController;

class AuthController extends BaseAuthController
{
    // 自定义登录view模板
    protected $view = 'admin::pages.login';

    /**
     * Show the login page.
     *
     * @return Content|\Illuminate\Http\RedirectResponse
     */
    public function getLogin(Content $content)
    {
        if ($this->guard()->check()) {
            return redirect($this->getRedirectPath());
        }
        // 判断是否安装的登录插件
        if (class_exists('WpLogin\Login\Http\Controllers\LoginController')) {
            return (new WpLoginController)->index($content);
        }
        // 开发登录页面插件
        return $content->full()->body(view($this->view));
    }

    /**
     * 安装系统
     */
    public function install(Request $request)
    {
        $data = $request->all();
        list($host, $port, $database, $username, $password) = [
            $data['server'],
            $data['port'],
            $data['database'],
            $data['username'],
            $data['password'],
        ];
        
        try {  
            $dsn = "mysql:host={$host};port={$port};charset=utf8mb4;collation=utf8mb4_general_ci;";  
            // 判断数据库是否存在，不存在创建一个
            $pdo = new \PDO($dsn, $username, $password);  
            $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);  
            $sql = "CREATE DATABASE IF NOT EXISTS `{$database}` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;";
            $pdo->exec($sql);  
            
            $dsn = "mysql:host={$host};port={$port};dbname={$database};charset=utf8mb4;collation=utf8mb4_general_ci;";  
            // 连接数据库
            $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); 
            // 执行sql文件
            $sqlFile = base_path('database/install.sql');
            $sql = file_get_contents($sqlFile);
            // dd($sql);
            // 选择数据库
            $pdo->exec("use `{$database}`;");
            // 执行sql语句
            $pdo->exec($sql);
            // 创建安装文件
            file_put_contents(public_path('install/lock/install.lock'), '');
            return response()->json(['status' => 'success', 'message' => '系统安装成功']);  
        } catch (\PDOException $e) {  
            // 捕获 PDO 异常，说明连接失败  
            return response()->json(['status' => 'error', 'message' => 'Database connection failed: ' . $e->getMessage()]);  
        }  
    }

    /**
     * 检查是否安装系统
    */
    public function checkInstall()
    {
        if (file_exists(public_path('install/lock/install.lock'))) {
            return redirect('/admin');
        }
        return view('install');
    }

    /**
     * Handle a login request.
     *
     * @param  Request  $request
     * @return mixed
     */
    public function postLogin(Request $request)
    {
        $credentials = $request->only([$this->username(), 'password']);
        $remember = (bool) $request->input('remember', false);

        /** @var \Illuminate\Validation\Validator $validator */
        $validator = Validator::make($credentials, [
            $this->username()   => 'required',
            'password'          => 'required',
        ]);

        if ($validator->fails()) {
            return $this->validationErrorsResponse($validator);
        }

        if ($this->guard()->attempt($credentials, $remember)) {
            return $this->sendLoginResponse($request);
        }

        return $this->validationErrorsResponse([
            $this->username() => $this->getFailedLoginMessage(),
        ]);
    }

    /**
     * Send the response after the user was authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    protected function sendLoginResponse(Request $request)
    {
        $request->session()->regenerate();

        $path = $this->getRedirectPath();
        $path =  $path . '/tab';
        return $this->response()
            ->success(trans('admin.login_successful'))
            ->locationToIntended($path)
            ->locationIf(Admin::app()->getEnabledApps(), $path)
            ->send();
    }

        /**
     * Model-form for user setting.
     *
     * @return Form
     */
    protected function settingForm()
    {
        return new Form(new Administrator(), function (Form $form) {
            $form->action(admin_url('auth/setting'));

            $form->disableCreatingCheck();
            $form->disableEditingCheck();
            $form->disableViewCheck();

            $form->tools(function (Form\Tools $tools) {
                $tools->disableView();
                $tools->disableDelete();
            });

            $form->display('username', trans('admin.username'));
            $form->text('name', trans('admin.name'))->required();
            $form->image('avatar', trans('admin.avatar'))->autoUpload();

            $form->password('old_password', trans('admin.old_password'));

            $form->password('password', trans('admin.password'))
                ->minLength(5)
                ->maxLength(20)
                ->customFormat(function ($v) {
                    if ($v == $this->password) {
                        return;
                    }

                    return $v;
                });
            $form->password('password_confirmation', trans('admin.password_confirmation'))->same('password');

            $form->ignore(['password_confirmation', 'old_password']);
            
            if (env('APP_DEBUG') == true) {
                $form->disableSubmitButton();
            }

            $form->saving(function (Form $form) {
                if ($form->password && $form->model()->password != $form->password) {
                    $form->password = bcrypt($form->password);
                }

                if (! $form->password) {
                    $form->deleteInput('password');
                }
            });

            $form->saved(function (Form $form) {
                return $form
                    ->response()
                    ->success(trans('admin.update_succeeded'))
                    ->redirect('auth/setting');
            });
        });
    }
}
